package com.xuanmiao.smsback.service.notice.impl;

import com.panshi.hujin2.base.common.util.DozerUtils;
import com.panshi.hujin2.base.domain.page.Page;
import com.xuanmiao.smsback.dao.mapper.BusinessNoticeMapper;
import com.xuanmiao.smsback.dao.mapper.MessagePushHistoryMapper;
import com.xuanmiao.smsback.dao.mapper.UserInfoMapper;
import com.xuanmiao.smsback.dao.model.BusinessNoticeDO;
import com.xuanmiao.smsback.dao.model.MessagePushHistoryDO;
import com.xuanmiao.smsback.dao.model.UserInfoDO;
import com.xuanmiao.smsback.domain.qo.BusinessNoticeQO;
import com.xuanmiao.smsback.domain.exception.NoticeException;
import com.xuanmiao.smsback.service.notice.INoticeService;
import com.xuanmiao.smsback.service.notice.bo.BusinessNoticeBO;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author shenJianKang
 * @date 2019/8/21 20:48
 */
@Service
public class NoticeServiceImpl implements INoticeService {
    private final Logger LOGGER = LoggerFactory.getLogger(getClass());


    @Autowired
    private BusinessNoticeMapper businessNoticeMapper;
    @Autowired
    private MessagePushHistoryMapper messagePushHistoryMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;


    @Override
    public List<BusinessNoticeBO> listBusinessNotice(BusinessNoticeQO qo) {
        if(qo == null){
            qo = new BusinessNoticeQO();
        }
        Integer count = businessNoticeMapper.countByParam(qo);
        Page page = qo.getPage();
        page.setTotalNumber(count);
        List<BusinessNoticeDO> doList = businessNoticeMapper.queryByParam(qo);
        if(CollectionUtils.isNotEmpty(doList)){
            return DozerUtils.convertList(doList, BusinessNoticeBO.class);
        }
        return Collections.emptyList();
    }

    @Override
    public int addBusinessNotice(BusinessNoticeBO bo) {
        if(bo == null){
            throw new NoticeException("addBusinessNotice param is null");
        }
        BusinessNoticeDO noticeDO = DozerUtils.convert(bo, BusinessNoticeDO.class);
        return businessNoticeMapper.insertSelective(noticeDO);
    }

    @Override
    public int updateBusinessNotice(BusinessNoticeBO bo) {
        if(bo == null || bo.getId()==null){
            throw new NoticeException("updateBusinessNotice param is null");
        }
        BusinessNoticeDO noticeDO = DozerUtils.convert(bo, BusinessNoticeDO.class);
        return businessNoticeMapper.updateByPrimaryKeySelective(noticeDO);
    }

    @Override
    @Transactional
    public void businessNoticeJob() {
        try {
            BusinessNoticeQO noticeQO = new BusinessNoticeQO();
            noticeQO.setSendStatus(1);//1-未发布
            noticeQO.setStatus(1);//1-有效
            noticeQO.setSendTime(new Date());
            List<BusinessNoticeDO>  noticeDOS = businessNoticeMapper.queryByParamNotLimit(noticeQO);
            if(CollectionUtils.isEmpty(noticeDOS)){
                XxlJobLogger.log("没有需要发布的公告");
                return;
            }

            //查詢所有激活狀態的用戶
            List<UserInfoDO> userInfoDOS = userInfoMapper.queryAllActivateInfo();
            if(CollectionUtils.isEmpty(userInfoDOS)){
                XxlJobLogger.log("没有用户信息");
                return;
            }

            List<Integer> updateIDS = new ArrayList<>();
            for(BusinessNoticeDO noticeDO:noticeDOS){
                updateIDS.add(noticeDO.getId());//更新需要的主键id

                for(UserInfoDO userInfoDO:userInfoDOS){
                    Integer userId = userInfoDO.getId();
                    MessagePushHistoryDO pushHistoryDO = new MessagePushHistoryDO();
                    pushHistoryDO.setUserId(userId);
                    pushHistoryDO.setType(-1);//-1;商户公告
                    pushHistoryDO.setTitle(noticeDO.getTitle());
                    pushHistoryDO.setText(noticeDO.getContent());
                    pushHistoryDO.setStatus(0);//未读
                    //// TODO: 2019/9/11   优化，商户多的时候改成批量插入
                    messagePushHistoryMapper.insertSelective(pushHistoryDO);
                }
            }

            //批量更新商家公告 为 ‘已发布’
            if(CollectionUtils.isNotEmpty(updateIDS)){
                businessNoticeMapper.batchUpdateSendStatusByPrimaryKey(updateIDS);
            }
        }catch (Exception e){
            LOGGER.error(e.getMessage(),e);
            XxlJobLogger.log(e.getMessage());
            throw e;
        }
    }

}
